import socket
import json 
import threading
import binascii

HOST = '127.0.0.1' 
PORT = 65432

def handle_client(conn):
    # 处理单个连接的代码
    data = b''
    while True:
        chunk = conn.recv(4096)
        if not chunk:
            break
        data += chunk
        # 解析JSON数据
    student = json.loads(data.decode('utf-8'))
        # 将图像数据转换为二进制格式
    id = student['id']
    name = student['name'] 
    print(f"Student name: {name}")  
    print(f"Student id: {id}")
    image_data_binary = binascii.unhexlify(student['image'])
        # 将二进制图像数据写入文件
    with open('photo.png', 'wb') as f:
        f.write(image_data_binary)
    print('Saved image file: photo.png')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    
    while True:
        conn, addr = s.accept() 
        client_thread = threading.Thread(target=handle_client, args=(conn,))
        client_thread.start()